/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.usercenter.service.impl;

import com.robam.cloud.common.bean.common.Constant;
import com.robam.cloud.common.bean.restful.entity.ServiceException;
import com.robam.cloud.common.bean.usercenter.entity.LoginAccount;
import com.robam.cloud.common.bean.usercenter.entity.User;
import com.robam.cloud.common.bean.usercenter.entity.UserSession;
import com.robam.cloud.common.bean.usercenter.enumspace.LoginAccountStatusEnum;
import com.robam.cloud.common.bean.usercenter.enumspace.UserStatusEnum;
import com.robam.cloud.common.bean.usercenter.form.RealNameForm;
import com.robam.cloud.common.util.BeanUtil;
import com.robam.cloud.common.util.RequestUtil;
import com.robam.cloud.common.util.StringUtil;
import com.robam.cloud.usercenter.dao.LoginAccountMapper;
import com.robam.cloud.usercenter.dao.UserMapper;
import com.robam.cloud.usercenter.helper.UserHelper;
import com.robam.cloud.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Description //开启事务PROPAGATION_REQUIRED  如果无跨库事务管理需求只需要PROPAGATION_REQUIRES_NEW 即可分库单独事务管理
 * @Author 薛铁琪
 * @CreateTime 2020-07-02 15:57
 * @Version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    LoginAccountMapper loginAccountMapper;
    @Autowired
    UserHelper userHelper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public LoginAccount initAccountUser(UserSession userSession) {
        User user = userSession.getUser();
        LoginAccount loginAccount = userSession.getLoginAccount();
        if (loginAccount == null) {
            throw new ServiceException("系统异常登陆账号初始化失败！");
        }
        Long isNewLoginAccount = loginAccountMapper.isNewLoginAccount(loginAccount.getPlatformId(), loginAccount.getAccountOpenid());

        if (isNewLoginAccount != null && isNewLoginAccount > 0) {//老帐号
            //更新老账号信息
            LoginAccount oldLoginAccount = loginAccountMapper.getOldLoginAccount(loginAccount.getPlatformId(), loginAccount.getAccountOpenid());
            oldLoginAccount.setNickname(loginAccount.getNickname());
            oldLoginAccount.setSex(loginAccount.getSex());
            if (StringUtil.isEmpty(oldLoginAccount.getZcip())) {
                oldLoginAccount.setZcip(loginAccount.getZcip());
            }
            if (oldLoginAccount.getZcsj() == null) {
                oldLoginAccount.setZcsj(loginAccount.getZcsj());
            }
            if (user != null) {//携带实名信息
                if (oldLoginAccount.getUserId() == null) {//原来没有实名的
                    User userInsertBack = userHelper.initUser(user);
                    oldLoginAccount.setUserId(userInsertBack.getId());
                    oldLoginAccount.setRzsj(new Date());
                    loginAccountMapper.updateByPrimaryKeySelective(oldLoginAccount);
                    return oldLoginAccount;
                } else {//原来有实名的
                    User oldUser = userMapper.selectByPrimaryKey(oldLoginAccount.getUserId());
                    if (Constant.LOGICDELETE.equals(oldUser.getZt()) || UserStatusEnum.DISABLED.getCode().equals(oldUser.getStatus())) {//无效的实名
                        User userInsertBack = userHelper.initUser(user);
                        oldLoginAccount.setUserId(userInsertBack.getId());
                        oldLoginAccount.setRzsj(new Date());
                        loginAccountMapper.updateByPrimaryKeySelective(oldLoginAccount);
                        return oldLoginAccount;
                    }
                    if (oldUser.getSfzmhm().equals(user.getSfzmhm())) {//同一个实名
                        userHelper.initUser(user);
                        loginAccountMapper.updateByPrimaryKeySelective(oldLoginAccount);
                        return oldLoginAccount;
                    } else {//不同的的实名
                        userHelper.exchangeUser(oldLoginAccount, user);
                        return loginAccountMapper.selectByPrimaryKey(oldLoginAccount.getId());
                    }
                }
            } else {//不携带实名信息
                loginAccountMapper.updateByPrimaryKeySelective(oldLoginAccount);
                return oldLoginAccount;
            }
        } else {//新账号
            loginAccount.setStatus(LoginAccountStatusEnum.NORMAL.getCode());
            loginAccount.setZcsj(new Date());
            loginAccount.setZt(Constant.LOGICNORMAL);
            if (user != null) {//携带实名信息
                User userInsertBack = userHelper.initUser(user);
                loginAccount.setUserId(userInsertBack.getId());
                loginAccountMapper.insertSelective(loginAccount);
                return loginAccount;
            } else {//不携带实名信息
                loginAccountMapper.insertSelective(loginAccount);
                return loginAccount;
            }
        }
    }

    @Override
    public Boolean realVerify(Long loginAccountId) {
        return userHelper.realVerify(loginAccountId);
    }

    @Override
    public User queryUserByAccountId(Long loginAccountId) {
        LoginAccount loginAccount = this.loginAccountMapper.selectByPrimaryKey(loginAccountId);
        if (loginAccount == null || (!LoginAccountStatusEnum.NORMAL.getCode().equals(loginAccount.getStatus())) || (!Constant.LOGICNORMAL.equals(loginAccount.getZt()))) {
            throw new ServiceException(String.format("loginAccount不存在请重新登录%s", loginAccountId));
        }
        Long userId = loginAccount.getUserId();
        if (userId == null) {
            throw new ServiceException("用户未实名");
        }
        User user = this.userMapper.selectByPrimaryKey(userId);
        if (user == null || (!UserStatusEnum.NORMAL.getCode().equals(user.getStatus())) || (!Constant.LOGICNORMAL.equals(user.getZt()))) {
            throw new ServiceException("用户未实名");
        }
        return user;
    }

    @Override
    public LoginAccount queryLoginAccountByAccountId(Long loginAccountId) {
        LoginAccount loginAccount = this.loginAccountMapper.selectByPrimaryKey(loginAccountId);
        if (loginAccount == null || (!LoginAccountStatusEnum.NORMAL.getCode().equals(loginAccount.getStatus())) || (!Constant.LOGICNORMAL.equals(loginAccount.getZt()))) {
            throw new ServiceException(String.format("loginAccount不存在请重新登录%s", loginAccountId));
        }
        return loginAccount;
    }

    @Override
    public void realName(RealNameForm realNameForm, HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader(Constant.TOKENNAME);
        //校验认证是否成功
        String bizNum = realNameForm.getBizNum();
        Boolean flag = Boolean.parseBoolean(String.valueOf(redisTemplate.opsForValue().get(Constant.FACEBIZNO + ":" + bizNum)));
        if (!flag) {
            throw new ServiceException("扫脸未通过，无法实名！");
        }
        redisTemplate.opsForValue().getOperations().delete(Constant.FACEBIZNO + ":" + token);
        redisTemplate.opsForValue().getOperations().delete(Constant.FACECERTIFYID + ":" + token);
        redisTemplate.opsForValue().getOperations().delete(Constant.FACEBIZNO + ":" + bizNum);
        //开始实名
        String accountId = String.valueOf(redisTemplate.opsForValue().get(Constant.TOKENNAME + ":" + token));
        LoginAccount loginAccount = loginAccountMapper.selectByPrimaryKey(Long.parseLong(accountId));
        User user = new User();
        BeanUtil.copyToObject(realNameForm, user);
        user.setZcip(RequestUtil.getIpAddress(httpServletRequest));
        user.setZcsj(new Date());
        if (loginAccount.getUserId() == null) {//原来没有实名的
            User userInsertBack = userHelper.initUser(user);
            loginAccount.setUserId(userInsertBack.getId());
            loginAccount.setRzsj(new Date());
            loginAccountMapper.updateByPrimaryKeySelective(loginAccount);
        } else {//原来有实名的
            User oldUser = userMapper.selectByPrimaryKey(loginAccount.getUserId());
            if (Constant.LOGICDELETE.equals(oldUser.getZt()) || UserStatusEnum.DISABLED.getCode().equals(oldUser.getStatus())) {//无效的实名
                User userInsertBack = userHelper.initUser(user);
                loginAccount.setUserId(userInsertBack.getId());
                loginAccount.setRzsj(new Date());
                loginAccountMapper.updateByPrimaryKeySelective(loginAccount);
            }
            if (oldUser.getSfzmhm().equals(user.getSfzmhm())) {//同一个实名
                userHelper.initUser(user);
                loginAccountMapper.updateByPrimaryKeySelective(loginAccount);
            } else {//不同的的实名
                userHelper.exchangeUser(loginAccount, user);
            }
        }
    }

    @Override
    public User queryCurrentUser(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader(Constant.TOKENNAME);
        String accountId = String.valueOf(redisTemplate.opsForValue().get(Constant.TOKENNAME + ":" + token));
        LoginAccount loginAccount = this.loginAccountMapper.selectByPrimaryKey(Long.parseLong(accountId));
        if (loginAccount == null || (!LoginAccountStatusEnum.NORMAL.getCode().equals(loginAccount.getStatus())) || (!Constant.LOGICNORMAL.equals(loginAccount.getZt()))) {
            throw new ServiceException(String.format("loginAccount不存在请重新登录%s", accountId));
        }
        Long userId = loginAccount.getUserId();
        if (userId == null) {
            throw new ServiceException("用户未实名");
        }
        User user = this.userMapper.selectByPrimaryKey(userId);
        if (user == null || (!UserStatusEnum.NORMAL.getCode().equals(user.getStatus())) || (!Constant.LOGICNORMAL.equals(user.getZt()))) {
            throw new ServiceException("用户未实名");
        }
        return user;
    }

    @Override
    public void subscribeEvent(String wechatOpenId) {
        LoginAccount loginAccount = loginAccountMapper.queryByOpenId(wechatOpenId);
        if (loginAccount != null) {
            LoginAccount update = new LoginAccount();
            update.setId(loginAccount.getId());
            update.setSfgz(LoginAccount.GZ);
            loginAccountMapper.updateByPrimaryKeySelective(update);
        }
    }

    @Override
    public void unSubscribeEvent(String wechatOpenId) {
        LoginAccount loginAccount = loginAccountMapper.queryByOpenId(wechatOpenId);
        if (loginAccount != null) {
            LoginAccount update = new LoginAccount();
            update.setId(loginAccount.getId());
            update.setSfgz(LoginAccount.WGZ);
            loginAccountMapper.updateByPrimaryKeySelective(update);
        }
    }
}
